package com.glsc.ngateway.opmanage.service.deposit;


import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.deposit.DepositoryBank;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.deposit.DepositoryDayStartData;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.deposit.DepositoryDayStartTrial;
import com.glsc.ngateway.common.base.repo.mysql.opmanagemain.deposit.DepositoryDayStartTrialRepository;
import com.glsc.ngateway.opmanage.utils.DateUtils;
import com.glsc.ngateway.opmanage.utils.SpecificationUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * 保证金每日试算(新)日初
 */

@Service
public class DepositoryDayStartTrialService {

    @Resource
    private DepositoryDayStartTrialRepository depositoryDayStartTrialRepository;

    @Resource
    private DepositoryBankService depositoryBankService;

    @Resource
    private DepositoryDayStartDataService depositoryDayStartDataService;

    @Resource
    private DepositoryDaySummaryService depositoryDaySummaryService;


    /**
     * 创建每日数据（日出）
     */

    @Transactional
    public void createDate() {

        List<DepositoryBank> banks = depositoryBankService.listAll();
        if (CollectionUtils.isEmpty(banks)) {
            return;
        }

        /**
         * 删除今日所有的数据
         */
        List<DepositoryDayStartTrial> oldDataList = listByDate(DateUtils.getNowDateString());
        if (CollectionUtils.isNotEmpty(oldDataList)) {
            List<Integer> oldIds = oldDataList.stream().map(DepositoryDayStartTrial::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(oldIds)) {
                deleteByIds(oldIds);
            }
        }

        //重新生成就今日数据
        List<DepositoryDayStartTrial> resList = Lists.newArrayList();

        for (DepositoryBank bank : banks) {
            //备付金不进行相关计算
            if (bank.getBankName().contains("备付金")) {
                continue;
            }

            DepositoryDayStartTrial trial = DepositoryDayStartTrial.builder().deleted("N").bankName(bank.getBankName()).build();
            resList.add(trial);

            trial.setEffectDate(DateUtils.getNowDateString());

            trial.setBankBalance(BigDecimal.ZERO);
            trial.setCounterBalance(BigDecimal.ZERO);

            //补充新意资金结算系统数据
            DepositoryDayStartData data = depositoryDayStartDataService.findByBankAccToday(bank.getAccount());
            if (Objects.nonNull(data)) {
                //T日日终银行余额 = 银行账户余额
                if (Objects.nonNull(data.getMarginTotalAmt())) {
                    trial.setBankBalance(data.getMarginTotalAmt());
                }
                //T日日终柜台余额
                if (Objects.nonNull(data.getMarginGtAmt())) {
                    trial.setCounterBalance(data.getMarginGtAmt());
                }
            }


            //T+1日日间设定存放比  或者 最低存放金额
            if (bank.getDepositFloorType().equals("1")) {
                trial.setStowageRate(bank.getDepositFloor());

                //T+1日日间余额
                trial.setDayBalance(trial.getCounterBalance().multiply(bank.getDepositFloor()).setScale(2, RoundingMode.HALF_UP).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
            } else {
                trial.setStowageLowAmount(bank.getDepositFloor());

                //T+1日日间余额
                trial.setDayBalance(bank.getDepositFloor());
            }

            //晨间调整值=T+1日日间余额-T日日终银行余额
            trial.setAdjustValue(trial.getDayBalance().subtract(trial.getBankBalance()));


        }

        if (CollectionUtils.isNotEmpty(resList)) {
            depositoryDayStartTrialRepository.saveAll(resList);
            depositoryDaySummaryService.create(resList);
        }


    }


    /**
     * 分页查找
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<DepositoryDayStartTrial> page(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<DepositoryDayStartTrial> page = depositoryDayStartTrialRepository.findAll(SpecificationUtil.buildSpecification(param, DepositoryDayStartTrial.class), pageable);

        return page;
    }


    /**
     * 根据日期查询所有的数据
     *
     * @param date
     * @return
     */
    public List<DepositoryDayStartTrial> listByDate(String date) {
        if (StringUtils.isEmpty(date)) {
            return null;
        }
        DepositoryDayStartTrial trial = DepositoryDayStartTrial.builder().effectDate(date).build();
        List<DepositoryDayStartTrial> datas = depositoryDayStartTrialRepository.findAll(Example.of(trial));
        return datas;
    }

    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    public DepositoryDayStartTrial findById(Integer id) {
        if (Objects.isNull(id)) {
            return null;
        }
        Optional<DepositoryDayStartTrial> optional = depositoryDayStartTrialRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 保存
     *
     * @param obj
     * @return
     */
    public DepositoryDayStartTrial save(DepositoryDayStartTrial obj) {
        if (Objects.isNull(obj)) {
            return null;
        }

        DepositoryDayStartTrial save = depositoryDayStartTrialRepository.save(obj);
        return save;
    }

    /**
     * 根据id删除
     */
    public void deleteById(Integer id) {
        if (Objects.isNull(id)) {
            return;
        }
        depositoryDayStartTrialRepository.deleteById(id);
    }

    /**
     * 根据id集合删除数据
     */
    public void deleteByIds(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }

        depositoryDayStartTrialRepository.deleteAllById(ids);
    }

}
